<?php

/* * 
 * 相册
 */
namespace Api\Model;
use Think\Model;
class AlbumModel extends Model {

    //映射
    protected $_map = array(
        'albumName' => 'album_name',
        'albumId' => 'album_id',
    );

    //获取相册
    public function getAlbumById($id) {

        $album = $this->where(array('album_id' => $id))->find();

        return $album;

    }

    //获取用户系统相册
    public function getSystemAlbumByUserId($userId) {

        $map['album_type'] = C('ALBUM_TYPE.SYSTEM');
        $map['user_id'] = $userId;

        $album = $this->where($map)->find();

        return $album;

    }

    //获取相册列表
    public function getAlbumListByUserId($userId) {

        $map['user_id'] = $userId;
        $list = $this
            ->field("album_id, album_name, photo_count, album_type")
            ->where($map)
            ->order("create_time ASC")
            ->select();

        foreach ($list as &$item) {
            $photo = D('photo')->getFirstPhotoByAlbumId($item['album_id']);
            
            $item['cover_image_url'] = $photo['thumb_url'];
        }

        return $list;

    }

    //添加相册
    public function addOrUpdateAlbum($userId) {

        //校验字段
        $validateRules = array(
            array('album_name', 'require'),
        );

        //自动完成
        $autoRules = array(
            array('create_time', 'getCurrentDate',self::MODEL_INSERT,'function'),
            array('user_id', $userId),
            array('photo_count', 0),
            array('album_type', C("ALBUM_TYPE.USER"))
        );

        $album = $this->validate($validateRules)->auto($autoRules)->create();

        if(!$album) {
            return 'ERROR_NECESSARY_DATA_NOT_FOUND';
        } else {

            if(isset($album['album_id'])) {

                $albumRecord = $this->getAlbumById($album['album_id']);

                //判断相册是否存在
                if(isNullOrEmpty($albumRecord)) {
                    return "ERROR_ALBUM_NOT_FOUND";
                }

                //判断是否为系统相册
                if($albumRecord['album_type'] == C("ALBUM_TYPE.SYSTEM")) {
                    return "ERROR_SYSTEM_ALBUM_CANNOT_EDIT_OR_DELETE";
                }

                $data['album_name'] = $album['album_name'];

                $this->where(array('album_id'=>$album['album_id']))->save($data);

            } else {
                //添加相册
                $this->add();
            }

            return 'SUCCESS';
        }

    }

    //删除相册
    public function deleteAlbumById($id) {

        $album = $this->getAlbumById($id);
        
        if(isNullOrEmpty($album)) {
            return "ERROR_ALBUM_NOT_FOUND";
        }

        if($album['album_type'] == C("ALBUM_TYPE.SYSTEM")) {
            return "ERROR_SYSTEM_ALBUM_CANNOT_EDIT_OR_DELETE";
        }

        $this->where(array('album_id' => $id))->delete();

        D('photo')->deletePhotoByAlbumId($id);

        return "SUCCESS";
    }

}

